package com.fenghongzhang.day018;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.fenghongzhang.day018.Food;
import com.fenghongzhang.day018.MyAdapter;
import com.fenghongzhang.day018.R;
import com.google.gson.Gson;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView lv;

    private List<Food.DataBean> data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        new Myeb().execute("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");

    }

    class Myeb extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... strings) {

            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                if (urlConnection.getResponseCode() == 200){
                    InputStream inputStream = urlConnection.getInputStream();
                    StringBuilder stringBuilder = new StringBuilder();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes))!= -1){
                        String s = new String(bytes, 0, len);
                        stringBuilder.append(s);
                    }
                    return stringBuilder.toString();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            Gson gson = new Gson();
            Food food = gson.fromJson(s, Food.class);
             data = food.getData();
            MyAdapter myAdapter = new MyAdapter(data, MainActivity.this);
            lv.setAdapter(myAdapter);

        }
    }
    private void initView() {
        lv = (ListView) findViewById(R.id.lv);
    }
}
